package com.gtlab1207.br_security.ctrls;


import cn.dev33.satoken.stp.StpUtil;
import com.gtlab1207.br_security.common.Codes;
import com.gtlab1207.br_security.common.FileUtil;
import com.gtlab1207.br_security.common.Result;
import com.gtlab1207.br_security.common.StringUtil;
import com.gtlab1207.br_security.models.domain.CasbinModel;
import com.gtlab1207.br_security.models.domain.User;
import com.gtlab1207.br_security.models.dto.AlterCasbinPolicy;
import com.gtlab1207.br_security.models.dto.SysUserEnforceEntity;
import com.gtlab1207.br_security.services.CheckCertService;
import com.gtlab1207.br_security.services.EnforcerService;
import com.gtlab1207.br_security.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;


@RestController
@RequestMapping("/abac")
public class AbacAuthCtrl extends BaseCtrl{
    @Autowired
    private EnforcerService enforcerService;
    @Autowired
    private CheckCertService checkCertService;
    @Autowired
    private UserService userService;

    String baseCertPath="C://Users//AceSpring//Desktop//cert//rsa//";

    @GetMapping("/model/info")
    public Result selectCasbinModel() {
        try {
            Map<String, Object> map = enforcerService.selectCasbinModel();
            return this.send(map);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    @PostMapping("/model/info")
    public Result insertCasbinModel(@Valid CasbinModel casbinModel) {
        try {
            Integer result = enforcerService.insertCasbinModel(casbinModel.getModelDef());
            if(result==0){
                return this.send(1101,"新增失败，请重新录入信息");
            }
            return this.send(Codes.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    @PutMapping("/model/info")
    public Result updateCasbinModel(@Valid CasbinModel casbinModel) {
        try {
            Integer result = enforcerService.updateCasbinModel(casbinModel);
            if(result==0){
                return this.send(1102,"修改失败，请重新输入信息");
            }
            return this.send(Codes.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 删除信息
     * @param modelId
     * @return
     */
    @DeleteMapping("/model/info/{modelId}")
    public Result deleteCasbinModel(@PathVariable String modelId){
        try {
            Integer result = enforcerService.deleteCasbinModel(modelId);
            if(result==0){
                return this.send(1100,"该信息不存在");
            }
            return this.send(Codes.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    @GetMapping("/policy/info")
    public Result showPolicies() {
        try {
            Map<String, Object> map = enforcerService.showPolicies();
            return this.send(map);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    @PostMapping("/policy/info")
    public Result savePolicy(@Valid AlterCasbinPolicy alterCasbinPolicy) {
        try {
            Integer result = enforcerService.savePolicy(alterCasbinPolicy.getPolicy());
            if(result==0){
                return this.send(1101,"该策略已存在");
            }
            return this.send(Codes.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    @PutMapping("/policy/info")
    public Result removePolicy(@Valid AlterCasbinPolicy alterCasbinPolicy) {
        try {
            Integer result = enforcerService.removePolicy(alterCasbinPolicy.getPolicy());
            if(result==0){
                return this.send(1100,"该信息不存在");
            }
            return this.send(Codes.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

//    @PostMapping("/ask")
//    public Result askPermission(@Valid SysUserEnforceEntity enforceEntity) {
//        try {
//            FileUtil.saveFile(enforceEntity.getFile());
//
//            String certPath = baseCertPath + "uploaded/" + enforceEntity.getAlias()+ ".p12";
//            //String certPath = baseCertPath + "uploaded//" + enforceEntity.getAlias()+ ".p12";
//
//            String checkResult = checkCertService.CheckCert(enforceEntity.getAlias(), enforceEntity.getPassword(), certPath);
//            if(checkResult.contains("error")) {
//                return this.send(1104, "证书校验不通过");
//            }else {
//                Map<String, String> resultMap = StringUtil.getMap(checkResult);
//                enforceEntity.setUserRole(resultMap.get("userRole"));
//                enforceEntity.setDepartment(resultMap.get("department"));
//                Integer result = enforcerService.enforceSysUser(enforceEntity);
//                if (result == 0) {
//                    return this.send(1103, "没有访问该服务的权限");
//                }
//                return this.send(1,"允许访问该服务");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return this.send(Codes.FAILED);
//        }
//    }

    @PostMapping("/ask")
    public Result askPermission(@Valid SysUserEnforceEntity enforceEntity) {
        try {
            if(StpUtil.getLoginIdByToken(enforceEntity.getToken())!=null){
                String username = StpUtil.getLoginIdByToken(enforceEntity.getToken()).toString();
                User user = userService.selectUser(username);
                enforceEntity.setUserRole(user.getUserRole());
                enforceEntity.setDepartment(user.getDepartment());
                Integer result = enforcerService.enforceSysUser(enforceEntity);
                if (result == 0) {
                    return this.send(1103, "没有访问该服务的权限");
                }
                return this.send(1,"允许访问该服务");
            }else {
                return this.send(Codes.NO_LOGIN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }
}
